import { ref, watch, nextTick, type Ref } from 'vue';
import { useRouter } from 'vue-router';
import { useFileManagerStore } from '@/stores/fileManagerStore.ts';
import type { FilesystemItemMeta } from '@/utils/indexedDBService';
import { ElMessage } from 'element-plus';

// ========================================================================
// START: useFileItemInteraction Composable Code (COPY THIS TO NEW FILE)
// ========================================================================

// Define possible interaction states (mostly for reference, actual logic uses selected/editing IDs)
// type InteractionState = 'idle' | 'hovered' | 'focused' | 'renaming' | 'focus-ghost' | 'opened';

// Configuration for timing (in milliseconds)
const DOUBLE_CLICK_DELAY = 500; // Max delay for double click detection (adjust as needed)
const RENAME_CLICK_DELAY_MIN = 600; // Min delay for second click to trigger rename (must be > DOUBLE_CLICK_DELAY)
const RENAME_CLICK_DELAY_MAX = 1500; // Max delay for second click to trigger rename (adjust as needed)

export function useFileItemInteraction(
    // Ref for the input element (passed from view)
    nameInputRef: Ref<any | null>,
    // Ref for the editing name model (passed from view)
    editingName: Ref<string>
) {
    console.log('[useFileItemInteraction] Initializing composable...');
    const router = useRouter();
    const fileManagerStore = useFileManagerStore();

    // --- State Refs ---
    const selectedItemId = ref<string | null>(null);
    const editingItemId = ref<string | null>(null);
    const focusGhostItemId = ref<string | null>(null); // Added state for focus-ghost
    const lastClickTimestamp = ref<number>(0);
    const lastClickedItemId = ref<string | null>(null);
    const clickTimeoutId = ref<ReturnType<typeof setTimeout> | null>(null);
    const isDoubleClick = ref<boolean>(false); // Flag to prevent click action after double click
    const isHoveringInputWhileRenaming = ref<boolean>(false); // State to track hover over input during rename
    // State for delayed context menu
    const contextMenuPendingTargetId = ref<string | null>(null);
    const contextMenuTimeoutId = ref<ReturnType<typeof setTimeout> | null>(null);

    // --- Private Helper Functions ---
    const _clearRenameTimer = () => {
        if (clickTimeoutId.value) {
            console.log('[useFileItemInteraction] Clearing rename timer.');
            clearTimeout(clickTimeoutId.value);
            clickTimeoutId.value = null;
        }
    };

    const _resetClickState = () => {
        console.log('[useFileItemInteraction] Resetting click state.');
        lastClickTimestamp.value = 0;
        lastClickedItemId.value = null;
        isDoubleClick.value = false;
        _clearRenameTimer();
    };

    // --- Exposed Functions ---

    /**
     * Handles single click events on a file/folder item.
     * Manages selection, initiates rename timer on second slow click.
     */
    const handleItemClick = (item: FilesystemItemMeta, event: MouseEvent) => {
        const now = Date.now();
        const clickedItemId = item.uuid;
        const target = event.target as HTMLElement;
        // Check if the click specifically hit the filename span (if it exists)
        const isFileNameClick = target.closest('.item-name') !== null;

        console.log(`[useFileItemInteraction handleItemClick] START - Item: ${clickedItemId}, Target: ${target.tagName}, FileNameClick: ${isFileNameClick}, TimeSinceLast: ${now - lastClickTimestamp.value}, CurrentSelected: ${selectedItemId.value}`);

        // Prevent interference if a double click was just handled
        if (isDoubleClick.value) {
            console.log('[useFileItemInteraction handleItemClick] Ignored due to recent double click');
            isDoubleClick.value = false; // Reset flag
            return;
        }

        _clearRenameTimer(); // Clear any pending rename timer

        // Clear pending context menu timer if a left click happens
        if (contextMenuTimeoutId.value) {
            console.log('[useFileItemInteraction handleItemClick] Clearing pending context menu timer.');
            clearTimeout(contextMenuTimeoutId.value);
            contextMenuTimeoutId.value = null;
            contextMenuPendingTargetId.value = null; // Reset pending target
        }

        if (selectedItemId.value === clickedItemId) {
            console.log('[useFileItemInteraction handleItemClick] Clicked on already selected item.');
            // Clicked on the already selected item
            const timeDiff = now - lastClickTimestamp.value;

            if (timeDiff > RENAME_CLICK_DELAY_MIN && timeDiff <= RENAME_CLICK_DELAY_MAX && isFileNameClick) {
                // Slow second click specifically on filename: Start Renaming
                console.log('[useFileItemInteraction handleItemClick] Slow click on filename -> Start Renaming');
                startRename(item);
            } else {
                // Either too fast (part of dblclick), too slow, or not on filename
                // Just update timestamp for potential future slow click
                console.log('[useFileItemInteraction handleItemClick] Click on selected item (not triggering rename yet).');
            }
        } else {
            // Clicked on a different item: Select it
            console.log(`[useFileItemInteraction handleItemClick] Selecting new item: ${clickedItemId}. Clearing ghost: ${focusGhostItemId.value}`);
            selectedItemId.value = clickedItemId;
            editingItemId.value = null; // Ensure not editing
            focusGhostItemId.value = null; // Clear focus ghost when selecting new item
        }

        lastClickTimestamp.value = now;
        lastClickedItemId.value = clickedItemId;
        console.log(`[useFileItemInteraction handleItemClick] END - Selected: ${selectedItemId.value}, LastClicked: ${lastClickedItemId.value}`);
    };

    /**
     * Handles double click events on a file/folder item.
     * Triggers the open action.
     */
    const handleItemDoubleClick = (item: FilesystemItemMeta, event: MouseEvent) => {
        console.log(`[useFileItemInteraction handleItemDoubleClick] START - Item: ${item.uuid} (${item.name})`);

        isDoubleClick.value = true; // Set flag to prevent subsequent click handlers
        _clearRenameTimer();
        _resetClickState();
        editingItemId.value = null; // Ensure this line is present and uncommented
        // Keep item selected visually? Maybe.
        // selectedItemId.value = item.uuid;

        // Perform open action
        if (item.type === 'folder') {
            console.log(`[useFileItemInteraction handleItemDoubleClick] Navigating to folder ${item.uuid}.`);
            fileManagerStore.navigateToFolder(item.uuid);
        } else {
            console.log(`[useFileItemInteraction handleItemDoubleClick] Loading file ${item.uuid}.`);
            fileManagerStore.loadFileIntoEditor(item.uuid)
                .then(() => {
                    console.log(`[useFileItemInteraction handleItemDoubleClick] File ${item.uuid} loaded, navigating to Editor.`);
                    router.push({ name: 'editor' });
                })
                .catch(err => {
                    console.error(`[useFileItemInteraction handleItemDoubleClick] Error loading file ${item.uuid}:`, err);
                    // Error message shown by store action
                });
        }
        // Reset flag shortly after to allow normal clicks again
        setTimeout(() => {
            console.log('[useFileItemInteraction handleItemDoubleClick] Resetting double click flag.');
            isDoubleClick.value = false;
         }, 50);
        console.log(`[useFileItemInteraction handleItemDoubleClick] END - Item: ${item.uuid}`);
    };

    /**
     * Initiates the renaming process for an item.
     */
    const startRename = (item: FilesystemItemMeta) => {
        console.log(`[useFileItemInteraction startRename] START - Item: ${item.uuid} (${item.name})`);
        // Ensure item is selected and not in ghost state when renaming starts
        console.log(`[useFileItemInteraction startRename] Forcing selection for item: ${item.uuid}. Clearing ghost: ${focusGhostItemId.value}`);
        selectedItemId.value = item.uuid;
        focusGhostItemId.value = null; // Clear any ghost state

        // Ensure item is selected first
        // selectedItemId.value = item.uuid; // Redundant, already set above
        editingItemId.value = item.uuid;
        editingName.value = item.name; // Populate input model
        _resetClickState(); // Clear click tracking state
        isHoveringInputWhileRenaming.value = false; // Reset input hover state on starting rename
        console.log(`[useFileItemInteraction startRename] Entering rename mode for: ${item.uuid}. Focusing input...`);

        // Focus input in the view (using nextTick)
        nextTick(() => {
            const inputInstance = (nameInputRef.value && nameInputRef.value.length > 0) ? nameInputRef.value[0] : null;
            console.log('[useFileItemInteraction startRename] nextTick: Focusing input instance:', inputInstance);
            inputInstance?.focus();
            inputInstance?.select();
        });
        console.log(`[useFileItemInteraction startRename] END - Editing ID: ${editingItemId.value}`);
    };

    /**
     * Confirms the rename operation.
     */
    const confirmRename = async () => {
        console.log(`[useFileItemInteraction confirmRename] START - Editing ID: ${editingItemId.value}, New Name: ${editingName.value}`);
        if (!editingItemId.value) {
            console.warn('[useFileItemInteraction confirmRename] Not in rename mode, exiting.');
             return; // Not in rename mode
        }

        const currentEditingId = editingItemId.value;
        const newName = editingName.value.trim();
        const originalItem = fileManagerStore.currentItems.find(i => i.uuid === currentEditingId);

        // Exit editing mode immediately (optimistic)
        console.log(`[useFileItemInteraction confirmRename] Exiting rename mode for ${currentEditingId}.`);
        editingItemId.value = null;
        _resetClickState();
        isHoveringInputWhileRenaming.value = false; // Reset input hover state on confirming rename

        if (!originalItem) {
            console.error('[useFileItemInteraction confirmRename] Original item not found!');
            return;
        }

        // Check if name actually changed
        if (newName === originalItem.name) {
            console.log('[useFileItemInteraction confirmRename] Name unchanged, rename cancelled.');
            return; // No actual rename needed
        }

        // Basic validation
        if (!newName) {
            console.warn('[useFileItemInteraction confirmRename] New name is empty, rename cancelled.');
            ElMessage.error('名称不能为空。');
            // Need to re-enter editing? This is tricky.
            // Maybe restore original name in store if needed?
            // For now, just exit.
            return;
        }
        if (newName.includes('/') || newName.includes('\\')) {
            console.warn(`[useFileItemInteraction confirmRename] Invalid new name: ${newName}. Rename cancelled.`);
            ElMessage.error('名称不能包含斜杠。');
            return;
        }

        try {
            console.log(`[useFileItemInteraction confirmRename] Attempting rename ${originalItem.name} -> ${newName} via store action.`);
            await fileManagerStore.renameItem(currentEditingId, newName, originalItem.type === 'folder');
            console.log('[useFileItemInteraction confirmRename] Rename successful in store.');
            // Success message handled by store
            // List updates automatically via store reactivity
        } catch (error: any) {
            console.error('[useFileItemInteraction confirmRename] Rename failed:', error);
            ElMessage.error(`重命名失败: ${error.message}`);
            // If rename failed (e.g., conflict), the list should refresh showing the old name.
            // No need to explicitly revert UI state here.
        }
        console.log(`[useFileItemInteraction confirmRename] END`);
    };

    /**
     * Cancels the current rename operation.
     */
    const cancelRename = () => {
        console.log(`[useFileItemInteraction cancelRename] START - Editing ID: ${editingItemId.value}`);
        if (!editingItemId.value) {
            console.warn('[useFileItemInteraction cancelRename] Not in rename mode, exiting.');
             return;
        }
        console.log('[useFileItemInteraction cancelRename] Cancelling rename for:', editingItemId.value);
        editingItemId.value = null;
        _resetClickState();
        isHoveringInputWhileRenaming.value = false; // Reset input hover state on cancelling rename
        // Optionally trigger a list refresh if needed, though usually not necessary
        console.log(`[useFileItemInteraction cancelRename] END`);
    };

    /**
     * Handles clicks outside of any file item (e.g., on the list background).
     */
    const handleClickOutside = () => {
        console.log(`[useFileItemInteraction handleClickOutside] START - Editing ID: ${editingItemId.value}, Selected ID: ${selectedItemId.value}, Ghost ID: ${focusGhostItemId.value}`);
        if (editingItemId.value) {
            const idBeforeRename = editingItemId.value;
            // If renaming, confirm the rename
            console.log('[useFileItemInteraction handleClickOutside] Was renaming -> Confirming Rename');
            confirmRename(); // This already nullifies editingItemId
            // Enter focus-ghost state after rename confirmation
            selectedItemId.value = null;
            focusGhostItemId.value = idBeforeRename;
            console.log(`[useFileItemInteraction handleClickOutside] Setting focus ghost after rename: ${focusGhostItemId.value}`);
        } else if (selectedItemId.value) {
            const idBeforeGhost = selectedItemId.value;
            // If an item is selected, deselect it and enter focus-ghost
            console.log('[useFileItemInteraction handleClickOutside] Item selected -> Deselecting Item, Entering Focus Ghost');
            selectedItemId.value = null;
            focusGhostItemId.value = idBeforeGhost;
            _resetClickState();
            console.log(`[useFileItemInteraction handleClickOutside] Setting focus ghost: ${focusGhostItemId.value}`);
        } else if (focusGhostItemId.value) {
            // If in focus-ghost, exit it
            console.log('[useFileItemInteraction handleClickOutside] In focus-ghost -> Exiting Focus Ghost');
            focusGhostItemId.value = null;
            _resetClickState();
        } else {
            // If clicked outside when nothing is selected/ghosted, clear any pending context menu
            console.log('[useFileItemInteraction handleClickOutside] Idle state -> Clearing pending context menu timer (if any).');
            if (contextMenuTimeoutId.value) {
                clearTimeout(contextMenuTimeoutId.value);
                contextMenuTimeoutId.value = null;
                contextMenuPendingTargetId.value = null;
            }
        }
        console.log(`[useFileItemInteraction handleClickOutside] END - Selected: ${selectedItemId.value}, Editing: ${editingItemId.value}, Ghost: ${focusGhostItemId.value}`);
        // If idle, do nothing
    };

    /**
     * Cancels the pending context menu timer.
     */
    const cancelContextMenu = () => {
        if (contextMenuTimeoutId.value) {
            console.log('[useFileItemInteraction cancelContextMenu] Clearing pending context menu timer explicitly.');
            clearTimeout(contextMenuTimeoutId.value);
            contextMenuTimeoutId.value = null;
            contextMenuPendingTargetId.value = null;
        }
    };

    // --- Input Hover Handlers --- (Keep logs minimal here)
    // Called when mouse enters the input element during rename
    const handleInputMouseEnter = () => {
        // console.log('[useFileItemInteraction] Input mouse enter.');
        if (editingItemId.value) { // Only active during rename
            isHoveringInputWhileRenaming.value = true;
        }
    };

    // Called when mouse leaves the input element during rename
    const handleInputMouseLeave = () => {
        // console.log('[useFileItemInteraction] Input mouse leave.');
        if (editingItemId.value) { // Only active during rename
            isHoveringInputWhileRenaming.value = false;
        }
    };

    // --- Watcher for focusing input when editing starts --- (No explicit watcher needed)
    // (Moved focus logic into startRename using nextTick)

    // --- Return values ---
    console.log('[useFileItemInteraction] Initialization complete. Returning state and functions.');
    return {
        selectedItemId,
        editingItemId,
        focusGhostItemId, // Export the new state
        isHoveringInputWhileRenaming, // Export hover state
        // Exposed handlers
        handleItemClick,
        handleItemDoubleClick,
        handleClickOutside,
        startRename, // Keep expose for right-click/F2
        confirmRename, // Keep expose for Enter key
        contextMenuPendingTargetId, // Export pending target ID ref
        contextMenuTimeoutId, // Export timeout ID ref
        cancelContextMenu, // Function to cancel pending menu
        cancelRename,  // Keep expose for Esc key
        handleInputMouseEnter, // Export hover handlers
        handleInputMouseLeave
    };
}

